#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      shoo
#
# Created:     12/06/2011
# Copyright:   (c) shoo 2011
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import logging
import dw
import rcv_forwarder
import conf
import sys
import re
import traceback
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

logging.getLogger().setLevel(logging.DEBUG)

def empty(s):
    if s==None or re.match(r'^\s*$',s):
        return True
    else:
        return False

# cronで起動されるメールチェックリクエストハンドラー
class CheckHandler(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain;charset=utf-8'

        config = conf.getConf()
        if empty(config.dwUser) or empty(config.dwPasswd) or empty(config.sender) or empty(config.to):
            # ドコモwebメールアカウント、送信元、送信先が未設定
            msg = "Error. Setup Conf.dwUser, Conf.dwPasswd, Conf.sender, Conf.to ."
            logging.error(msg)
            self.response.out.write(msg)
            return
        config.dwUser = config.dwUser.strip()
        config.dwPasswd = config.dwPasswd.strip()
        config.sender = config.sender.strip()
        config.to = config.to.strip()

        dwm = dw.Dw(config.dwUser, config.dwPasswd)
        # ログイン
        res = dwm.login()
        try:
            # メール一覧取得
            html = dwm.mailListStart()
            ids = dwm.parseMailList(html)
            if len(ids)==0:
                # 受信メールが0件
                msg = "0 mail"
                self.response.out.write(msg)
                logging.info(msg)
                return

            if config.last_id==0:
                # 最初のチェックでは転送しない
                config.last_id = ids[-1]
                config.put()
                msg = "first check"
                self.response.out.write(msg)
                logging.info(msg)
                return

            for i, num in enumerate(ids):
                if num<=config.last_id:
                    continue
                mail = dwm.getMail(num)
                email = rcv_forwarder.RcvForwarder(config.sender, config.to, dwm.opener, config.image_link, config.subject_prefix, config.subject_suffix)
                email.forward(mail)
                config.last_id = num
                config.put() # 最終転送メールIDを更新
                self.outMail(mail)
        except Exception, val:
            msg = "Error "+str(val)+"/"+str(sys.exc_info()[0])
            msg += traceback.format_exc()
            logging.error(msg)
            self.response.out.write(msg)
            raise val

    # http応答にメール情報を出力
    def outMail(self, mail):
        msg = "Forward Subject: [%s]  , From: [%s]\r\n" % (mail['subject'],  ", ".join(mail['from']))
        self.response.out.write(msg)

def main():
    application = webapp.WSGIApplication([('/dw/check', CheckHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
